import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import 'package:intl/intl.dart';

import '../../common/api/home_api.dart';
import '../../common/const/app_color_const.dart';
import '../../common/const/app_style_const.dart';
import '../../common/type/bottom_action_sheet_type.dart';
import '../../common/type/user_type.dart';
import '../../common/util/common_util.dart';
import '../../common/util/store_util.dart';
import '../../widget/bottom_action_sheet.dart';
import '../../widget/card_container.dart';
import '../../widget/empty.dart';
import '../../widget/gradient_btn.dart';
import '../../widget/ripple_container.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  bool workAuditVisible = false;
  bool stockOrderVisible = false;
  String dataNow = '';

  Map<dynamic, dynamic> workOrderInfo = {};

  List<dynamic> todayAgendaList = [];

  List<dynamic> stockOrderList = [];

  List<dynamic> workAuditList = [];

  List<Map<String, dynamic>> menuList = [
    {
      "key": "siteManagement",
      "icon": "assets/images/home/site.png",
      "label": "基地管理",
      "page": "/siteManagement",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "staffManagement",
      "icon": "assets/images/home/staff.png",
      "label": "员工管理",
      "page": "/staffManagement",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "roleManger",
      "icon": "assets/images/home/role.png",
      "label": "角色管理",
      "page": "/roleManagement",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "liveAudit",
      "icon": "assets/images/home/live.png",
      "label": "主播审核",
      "page": "/liveAudit",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "roomManagement",
      "icon": "assets/images/home/room.png",
      "label": "房间管理",
      "page": "/roomManagement",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "workAudit",
      "icon": "assets/images/home/work_audit.png",
      "label": "工作审核",
      "page": "/workAudit",
      "emptyMenu": true,
      "arguments":{}
    },
    {
      "key": "stockOrder",
      "icon": "assets/images/home/stock_order.png",
      "label": "备货工单",
      "page": "/stockOrder",
      "emptyMenu": true,
      "arguments":{}
    },
    {
      "key": "assignWorkOrder",
      "icon": "assets/images/home/assign.png",
      "label": "工单指派",
      "page": "/assignWorkOrder",
      "emptyMenu": true,
      "arguments":null
    },
    {
      "key": "supplierAudit",
      "icon": "assets/images/home/supplier.png",
      "label": "供应商审核",
      "page": "/supplierAudit",
      "emptyMenu": true,
      "arguments":null
    },
  ];

  @override
  void initState() {
    super.initState();
    initData();
  }

  initData() {
    dataNow = DateFormat('yyyy年MM年dd日 EEEE', "zh_CN").format(DateTime.now());
    getWorkOrderInfo();
    checkAuth();
  }

  getWorkOrderInfo() {
    HomeApi.getWorkOrderInfo({}).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        var data = res.data["data"];
        todayAgendaList = data["todayScheList"];
        stockOrderList = data["ingList"];
        workAuditList = data["waitReplyOrCheckList"];

        setState(() {});
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  checkAuth() {
    UserInfoType userInfo = StoreUtil.getUserInfo();
    if (null != userInfo.authList && userInfo.authList!.isNotEmpty) {
      for (var authKey in userInfo.authList ?? []) {
        if (authKey == "workAudit") {
          workAuditVisible = true;
        }
        if (authKey == "stockOrder") {
          stockOrderVisible = true;
        }
      }
    }

    setState(() {});
  }

  exitLogin() {
    CommonUtil.showSingleConfirmDialog(
        "exitLoginConfirmDialog", 135, "您确认退出登录吗？", (cb) {
      cb();
      StoreUtil.clear();
      Navigator.of(context).pushNamedAndRemoveUntil("/login", (route) => false);
    });
  }

  toStockOrderDetail(item) {
    Navigator.of(context).pushNamed("");
  }

  todayAgendaBodyBuilder(context) {
    bool isEmpty = false;
    List<Widget> rippleContainerList = [];
    if (todayAgendaList.isEmpty) {
      rippleContainerList.add(const Empty());
      isEmpty = true;
    } else {
      for (var i = 0; i < todayAgendaList.length; i++) {
        Map todayAgenda = todayAgendaList[i];
        rippleContainerList.add(RippleContainer(
            onTap: () => {toStockOrderDetail(todayAgenda)},
            child: Row(
              children: [
                Container(
                  height: 35,
                  width: 30,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    (i + 1).toString(),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  height: 35,
                  width: 90,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    todayAgenda["bookStartTime"] +
                        "-" +
                        todayAgenda["bookEndTime"],
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Expanded(
                    child: Container(
                  height: 35,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    todayAgenda["liveRoomNo"],
                    overflow: TextOverflow.ellipsis,
                  ),
                )),
                Container(
                  height: 35,
                  width: 65,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    todayAgenda["bookUserName"],
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  height: 35,
                  width: 15,
                  padding: const EdgeInsets.only(top: 2.0),
                  alignment: Alignment.centerRight,
                  child: const Icon(
                    Icons.chevron_right,
                    color: grayColor,
                    size: 16,
                  ),
                ),
              ],
            )));
      }
    }

    return Container(
      padding: const EdgeInsets.only(top: 10.0),
      height: rippleContainerList.length >= 2
          ? 115
          : isEmpty
              ? 35
              : rippleContainerList.length * 35 + 10,
      child: SingleChildScrollView(
          controller: ScrollController(),
          child: Column(
            children: rippleContainerList,
          )),
    );
  }

  stockOrderBodyBuilder(context) {
    List<RippleContainer> rippleContainerList = [];

    for (var i = 0; i < stockOrderList.length; i++) {
      rippleContainerList.add(RippleContainer(
          child: Row(
            children: [
              Expanded(
                  child: Container(
                height: 35,
                alignment: Alignment.centerLeft,
                child: Text(
                  stockOrderList[i]["statusTitle"],
                  overflow: TextOverflow.ellipsis,
                ),
              )),
              Container(
                width: 45,
                height: 35,
                alignment: Alignment.centerLeft,
                child: Text(
                  stockOrderList[i]["num"].toString(),
                  style: const TextStyle(color: redAccentColor),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                width: 45,
                height: 35,
                alignment: Alignment.centerRight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    const Text(
                      "详情",
                      style: TextStyle(color: grayColor),
                      overflow: TextOverflow.ellipsis,
                    ),
                    Container(
                      padding: const EdgeInsets.only(top: 2.0),
                      alignment: Alignment.centerRight,
                      child: const Icon(
                        Icons.chevron_right,
                        color: grayColor,
                        size: 16,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          onTap: () {
            print("---");
          }));
    }

    return SingleChildScrollView(
      controller: ScrollController(),
      child: Column(
        children: rippleContainerList,
      ),
    );
  }

  workAuditBodyBuilder(context) {
    List<RippleContainer> rippleContainerList = [];

    for (var i = 0; i < workAuditList.length; i++) {
      rippleContainerList.add(RippleContainer(
          child: Row(
            children: [
              Expanded(
                  child: Container(
                height: 35,
                alignment: Alignment.centerLeft,
                child: Text(
                  workAuditList[i]["statusTitle"],
                  overflow: TextOverflow.ellipsis,
                ),
              )),
              Container(
                width: 45,
                height: 35,
                alignment: Alignment.centerLeft,
                child: Text(
                  workAuditList[i]["num"].toString(),
                  style: const TextStyle(color: redAccentColor),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                width: 45,
                height: 35,
                alignment: Alignment.centerRight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    const Text(
                      "详情",
                      style: TextStyle(color: grayColor),
                      overflow: TextOverflow.ellipsis,
                    ),
                    Container(
                      padding: const EdgeInsets.only(top: 2.0),
                      alignment: Alignment.centerRight,
                      child: const Icon(
                        Icons.chevron_right,
                        color: grayColor,
                        size: 16,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          onTap: () {
            print("---");
          }));
    }

    return SingleChildScrollView(
      controller: ScrollController(),
      child: Column(
        children: rippleContainerList,
      ),
    );
  }

  myFunctionBodyBuilder(context) {
    List<Map<String, dynamic>> authMenuList = [];
    UserInfoType userInfo = StoreUtil.getUserInfo();
    if (null != userInfo.authList && userInfo.authList!.isNotEmpty) {
      for (var element in menuList) {
        for (var authKey in userInfo.authList ?? []) {
          if (element["key"] == authKey) {
            authMenuList.add({...element, "emptyMenu": false});
            break;
          }
        }
      }
    }

    List<TableRow> tableRows = [];
    int remainder = authMenuList.length % 3;
    if (remainder > 0) {
      for (var i = remainder; i <= 3; i++) {
        authMenuList.add({"emptyMenu": true});
      }
    }

    int size = authMenuList.length ~/ 3;
    int index = 0;
    for (var i = 0; i < size; i++) {
      List<Widget> rippleContainers = [];
      for (var j = 0; j < 3; j++) {
        Map menu = authMenuList[index];
        if (menu["emptyMenu"]) {
          rippleContainers.add(Container());
        } else {
          rippleContainers.add(RippleContainer(
              onTap: () => {
                if(null!=menu["arguments"]){
                  Navigator.of(context).pushNamed(menu["page"],arguments: menu["arguments"])
                }else{
                  Navigator.of(context).pushNamed(menu["page"])
                }

              },
              child: Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(bottom: 12.0, top: 12.0),
                child: Column(
                  children: [
                    Image.asset(
                      menu["icon"],
                      width: 40,
                      height: 40,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 5.0),
                      child: Text(
                        menu["label"],
                        overflow: TextOverflow.ellipsis,
                        style:
                            const TextStyle(fontSize: 12, color: blackColor66),
                      ),
                    )
                  ],
                ),
              )));
        }
        index++;
      }
      tableRows.add(TableRow(children: rippleContainers));
    }

    return Table(
      columnWidths: const {
        0: FlexColumnWidth(33.333333),
        1: FlexColumnWidth(33.333333),
        2: FlexColumnWidth(33.333333)
      },
      children: tableRows,
    );
  }

  Widget appBarActionSheet() {
    return BottomActionSheet(
      actionList: [
        BottomActionSheetItemType(
            label: "个人资料",
            onPressed: () {
              Navigator.of(context).popAndPushNamed("/userInfo");
            }),
        BottomActionSheetItemType(
            label: "退出登录",
            onPressed: () {
              exitLogin();
            })
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            onPressed: () {
              showCupertinoModalPopup(
                context: context,
                builder: (BuildContext context) => appBarActionSheet(),
              ).then((value) {});
            },
            icon: const Icon(
              Icons.account_circle_outlined,
              size: 22.5,
            ),
          ),
          title: const Text("主页"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 2.0),
              child: IconButton(
                icon: const Icon(
                  Icons.refresh,
                  size: 25,
                ),
                onPressed: () {
                  initData();
                },
              ),
            ),
          ],
        ),
        body: SingleChildScrollView(
            controller: ScrollController(),
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  if (stockOrderVisible)
                    CardContainer(
                        title: "今日日程",
                        margin: const EdgeInsets.only(bottom: 10.0),
                        titleRightBuilder: (context) => Text(
                              dataNow,
                              style: const TextStyle(color: grayColor),
                            ),
                        bodyBuilder: (context) =>
                            todayAgendaBodyBuilder(context)),
                  if (stockOrderVisible)
                    CardContainer(
                      title: "处理工单",
                      margin: const EdgeInsets.only(bottom: 10.0),
                      titleRightBuilder: (context) => GradientBtn(
                          padding: const EdgeInsets.only(
                              left: 7.0, top: 2.0, bottom: 3.0),
                          label: "查看全部工单",
                          labelRightBuilder: (context) => Container(
                                padding: const EdgeInsets.only(top: 2.0),
                                alignment: Alignment.centerRight,
                                child: const Icon(
                                  Icons.chevron_right,
                                  color: primaryColor,
                                  size: 16,
                                ),
                              ),
                          onTap: () => {}),
                      bodyBuilder: (context) => stockOrderBodyBuilder(context),
                    ),
                  if (workAuditVisible)
                    CardContainer(
                      title: "工作审核",
                      margin: const EdgeInsets.only(bottom: 10.0),
                      titleRightBuilder: (context) => GradientBtn(
                          padding: const EdgeInsets.only(
                              left: 7.0, top: 2.0, bottom: 3.0),
                          label: "查看全部审核",
                          labelRightBuilder: (context) => Container(
                                padding: const EdgeInsets.only(top: 2.0),
                                alignment: Alignment.centerRight,
                                child: const Icon(
                                  Icons.chevron_right,
                                  color: primaryColor,
                                  size: 16,
                                ),
                              ),
                          onTap: () => {}),
                      bodyBuilder: (context) => workAuditBodyBuilder(context),
                    ),
                  CardContainer(
                    title: "我的功能",
                    margin: const EdgeInsets.only(bottom: 10.0),
                    bodyPadding: const EdgeInsets.only(
                        bottom: 15.0, left: 3.0, right: 3.0),
                    bodyBuilder: (context) => myFunctionBodyBuilder(context),
                  )
                ],
              ),
            )));
  }
}
